package gdou.gym.sys.order;

import gdou.gym.exception.ForbiddenException;
import gdou.gym.exception.StateCode;
import gdou.gym.exception.SysException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class RemainInterceptor implements HandlerInterceptor {
    @Autowired
    private Remain remain;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ss = request.getParameter("spaceTimeID");
        if (ss == null) throw new ForbiddenException();
        //跨域重点!!!!

        if ("OPTIONS".equals(request.getMethod())) return true;
        Integer spaceTimeID = Integer.valueOf(ss);
        if (remain.decrease(spaceTimeID, 1)) return true;
        throw new SysException(StateCode.ORDER_ERROR);
    }
}
